package com.tang.interceptor;

import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
 * @Author Tom
 * @ClassName LoginInterceptor
 * @Date 2021/10/23 22:01
 */
public class LoginInterceptor implements HandlerInterceptor {

    //在请求处理的方法之前执行
    //如果返回true执行下一个拦截器
    //如果返回false就不执行下一个拦截器
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession session = request.getSession();
        //获取资源请求路径
        String uri = request.getRequestURI();
        System.out.println(uri);
        //判断是否包含登录相关资源路径
        if (uri.contains("/login")||uri.contains("/code")) {
            //包含，用户就是想登录。放行
            return true;
        } else {
            //不包含，需要验证用户是否登录
            //从获取session中获取user
            Object administrator = session.getAttribute("user");
            if (administrator != null) {
                //登录了放行
                return true;
            } else {
                //没有登录。跳转登录页面
                request.setAttribute("msg", "您尚未登录，请先登录");
                request.getRequestDispatcher("/WEB-INF/jsp/login.jsp").forward(request,response);
                return false;
            }
        }
    }
}
